#!/usr/bin/python
#-*-coding: utf-8 -*-

__all__ = [u'GuiPart']

########## DO NOT CHANGE THESE LINES ###########################################
import sys
from pylot.core import (ENCODING, Path)
try : __file__
except NameError : co = sys._getframe(0).f_code ; __file__ = co.co_filename
ufile = __file__.decode(ENCODING)
if ufile.strip() : PLUGIN_PATH = Path(ufile).abspath().parent
else : PLUGIN_PATH = Path(u'.').abspath()
########## DO NOT CHANGE THESE LINES ###########################################

from PyQt4 import QtGui
from PyQt4.QtGui import QTreeWidgetItem, QApplication
from PyQt4.QtCore import *
from pylot.core import (check_type, ENCODING, Path, hardbook, Utils)

from handler import HandlerPart
from pylot.qtgui import (load_designer_file, GuiAutoWidget)

_GuiPart, WidgetClass = load_designer_file(u'designer.ui', [PLUGIN_PATH])
###################################################
class GuiPart(WidgetClass, GuiAutoWidget, _GuiPart):
  u"""
  A very simple divider
  """
  def __init__(self, handler=None):
    if handler is None :
      handler = HandlerPart()
      handler.init()
    self.handler = handler
    self._initFromHandler()
    GuiAutoWidget.__init__(self, handler)
    #WidgetClass.__init__(self)
    self.ok = False
    self.setupUi(self) # Designer file initialization 
    self.pathbook[u'project'] = hardbook(u'projects')
    self.adjustSize()
    self.big_size = self.size()
    self.small_size = self.widgetMain.size()
    self._chooseTemplate(True)
    self.setMaximumHeight(self.small_size.height())
    self.lineEditRoot.setText(self.pathbook(u'project'))
    self.lineEditName.setText(u"No_name")
    # Widget creation
    self._createActions()
    self._createConnexions()
    #self._createMenu()
    #self._createToolBars()
  # ============================================================================
  def _getName(self):return unicode(self.lineEditName.text())
  # ============================================================================
  def _getTemplate(self):return unicode(self.lineEditTemplate.text())
  # ============================================================================
  def _getDir(self): return unicode(self.lineEditRoot.text())
  # ============================================================================
  # Widget Creation
  # ============================================================================
  # ============================================================================
  def _createConnexions(self):
    self.connect(self.buttonBox, SIGNAL(u"accepted()"), self._newproject)
    self.connect(self.pushButtonProjectsDir, SIGNAL(u"clicked()"), self._chooseProjectsDir)
    self.connect(self.treeWidgetTemplates, SIGNAL(u"itemDoubleClicked (QTreeWidgetItem *,int)"), self._setTemplate)
    self.connect(self.treeWidgetTemplates, SIGNAL(u"itemEntered (QTreeWidgetItem *,int)"), self._setTemplate)
    self.connect(self.treeWidgetTemplates, SIGNAL(u" currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )"), self._setTemplate)
  # ============================================================================
  def _createMenu(self):
    self.menu_example = QtGui.QMenu()
    self.menu_example.setObjectName(u'menu_example')
    self.addMenu_(self.menu_example)
  # ============================================================================
  def _createToolBars(self):
    self.tool_bar_example = QtGui.QToolBar()
    self.tool_bar_example.setObjectName(u'tool_bar_example')
    self.addToolBar_(self.tool_bar_example)
  # ============================================================================
  def _setSize(self, s):
    self.setMinimumSize(s)
    self.setBaseSize(s)
  # ============================================================================
  # Widget dynamic changes
  # ============================================================================
  def _toTreeWidget(self, examples):
     u"""
     transforme examples en liste de QTreeWidgetItem
     @return: list de QTreeWidgetItem
     @rtype: list of QTreeWidgetItem
     """
     items = []
     for d in examples:
      item = QTreeWidgetItem()
      item.setText(0, d[0].parent.parent.name)
      items.append(item)
      for ex in d :
        child = QTreeWidgetItem(item)
        child.setText(1, ex.name)
        child.setText(2, ex)
     return items
  # ============================================================================
  def _suggestName(self, pj):
    u"""
    Suggests a name for directory to store new project.
    If template is NavierStockes, and if NavierStockes directory yet exists in Projects directory, name NavierStockes-01 is suggested.
    @param pj: template directory base name
    """
    i = 0
    p = pj
    dirname = unicode(self.lineEditRoot.text())
    path= Path(dirname)
    if (path.isdir()):
        while Path(path,p).isdir():
          i = i + 1
          p = pj + u'-%02d' % i
    return p
  # ============================================================================
  def _setTemplate(self, item, col):
    u"""
    Remplissage des champs texte lineEditTemplate (nom de l'exemple) et lineEditName (nom du projet).

    Cette méthode est appelée lorsque la colonne 'col' de l'item 'item' du QTreeWidget a été double -cliquée.
    @param item: l'item cliqué, de type QTreeWidgetItem
    @param col: numéro de la colonne cliquée, inutilisé.
    """
    #print "### GuiNewProject._setTemplate, item=%s, col=%s"%(item.text(1), col)
    if item.text(0):
      self.lineEditTemplate.setText(u"No template")#ya du texte en colonne 0, -> c'est pas un modele
      self.lineEditName.setText(u"No name")
    else:
      self.lineEditTemplate.setText(item.text(2))
      self.lineEditName.setText(self._suggestName(unicode(item.text(1))))
      self.handler.exampleName = unicode(item.text(1))
  # ============================================================================
  def _chooseTemplate(self, v) :
    u"""
    Open template part of main widget, and populate it with examples/templates.
    @param v: if True, resize widget to big size (i.e. show treeWidget)
    @type v: bool
    """
    self.treeWidgetTemplates.setVisible(v)
    if v :
      self._setSize(self.big_size)
      self.setMaximumHeight(99999)
    else:
      self.setSize(self.small_size)
      self.setMaximumHeight(self.small_size.height())
    self.treeWidgetTemplates.clear()
    for dirname in self.examplesDirs :
      templates = self._toTreeWidget(self.examples[dirname])
      for template in templates :
        self.treeWidgetTemplates.addTopLevelItem(template)

    self.treeWidgetTemplates.expandAll()
    self.treeWidgetTemplates.resizeColumnToContents (0)
    self.treeWidgetTemplates.resizeColumnToContents (1)
    self.treeWidgetTemplates.sortByColumn (1, Qt.AscendingOrder)
  # ============================================================================
  def _chooseProjectsDir(self) :
    u"""
    Allow to choose user projects directory, where choosen example will be copied.
    """
    path = QtGui.QFileDialog.getExistingDirectory (self, self.tr_(u"Choose project directory"))
    if path :
        self.lineEditRoot.setText(QApplication.translate(u"dialogNewProject", path, None, QApplication.UnicodeUTF8))
        dirname = unicode(self.lineEditRoot.text())
        self.pathbook[u'project'] = Path(dirname).abspath()
        self.lineEditName.setText(self._suggestName(self.handler.exampleName))
  # ============================================================================
  def _translate(self):
    return
    pass
    self._setTexts([
      (self.menu_example, self.tr_(u'Example')),
      (self.tool_bar_example, self.tr_(u'Example ToolBar'))
      ])

  def _updateData(self):
    pass

  def _refresh(self):
    pass

  def _decorate (self):
    pass
    # self._setIcons([
    #  (self.action_example, u'example.png')
    #  ])

  def _fillToolBars(self, level):
    pass
    #self._fill(self.tool_bar_example, [
    #  self.action_example,
    #  ])

  def _fillMenus(self, level):
    pass
    #self._fill(self.menu_example, [
    #  self.action_example,
    #  ])
  # ============================================================================
  # Widget/HandlerPart Connections
  # ============================================================================
  def _initFromHandler(self):
     self.pathbook = self.handler.pathbook
     self.examplesDirs = self.handler.examplesDirs
     self.examples = self.handler.examples
  # ============================================================================
  def _newproject(self):
    dirname = unicode(self.lineEditRoot.text())
    self.pathbook[u'project'] = Path(dirname, self._getName()).abspath()
    self.ok = self.handler.newProject(self._getTemplate(), self.pathbook[u'project'])
    if (self.ok):
         self.emit(SIGNAL('newProject'), Path(dirname, self._getName()).abspath())
  # ============================================================================
  # Widget Public Methods
  # ============================================================================
  # define here all methods you want to be reachable outside this widget
  # these methods are useful to embed this plugin in an other
  def updateExampleName(self):
        self.lineEditName.setText(self._suggestName(self.handler.exampleName))
if __name__ == u"__main__":
  from PyQt4.QtGui import QApplication
  app = QApplication([])
  gui = GuiPart()
  gui.show()
  ret = app.exec_()
